package com.aduerr.v1shouyin.mvp.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.aduerr.v1shouyin.R;
import com.aduerr.v1shouyin.entity.OrderGetPosOrderLEntity;
import com.aduerr.v1shouyin.http.APIRetrofit;
import com.aduerr.v1shouyin.http.RXRequest;
import com.aduerr.v1shouyin.mvp.activity.BangGuidActivity;
import com.aduerr.v1shouyin.mvp.activity.LoginActivity;
import com.aduerr.v1shouyin.mvp.adpter.OrderinquireStickrecycleadpter;
import com.aduerr.v1shouyin.util.LogUtils;
import com.aduerr.v1shouyin.util.PeixiDividerGridItemDecoration;
import com.aduerr.v1shouyin.util.SharedPreferencesUtils;
import com.aduerr.v1shouyin.util.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 类名: SaomaFregment
 * 此类用途: ---
 *
 * @Author: peixi
 * @Date: 2017-12-13 20:11
 * @Email: cr7inmanchester.com
 * @FileName: com.aduer.shouyin.mvp.fragment.SaomaFregment.java
 */
public class SaomaFregment extends Fragment {
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    Unbinder unbinder;
    private OrderinquireStickrecycleadpter stickrecycleadpter;
    private int page = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.saomafregment, null, false);
        unbinder = ButterKnife.bind(this, inflate);
        return inflate;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initDate();
    }

    private void initDate() {
        recyclerview.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.VERTICAL, false));
        recyclerview.addItemDecoration(new PeixiDividerGridItemDecoration(getActivity()
                , PeixiDividerGridItemDecoration.VERTICAL_LIST, 8, R.color.bg_ios));
        stickrecycleadpter = new OrderinquireStickrecycleadpter(getActivity());
        StickyRecyclerHeadersDecoration headersDecor =
                new StickyRecyclerHeadersDecoration(stickrecycleadpter); //绑定之前的adapter

        stickrecycleadpter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
            @Override
            public void onChanged() {
                headersDecor.invalidateHeaders();
            }
        });
        recyclerview.addItemDecoration(headersDecor);
        recyclerview.setAdapter(stickrecycleadpter);

//        final RefreshLayout refreshLayout = (RefreshLayout) findViewById(R.id
//        .refreshLayout);
        refreshLayout.setEnableAutoLoadmore(true);//开启自动加载功能（非必须）
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData(getActivity(), 1);
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 2000);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        initData(getActivity(), page);
                        refreshlayout.finishLoadmore();

                    }
                }, 2000);
            }
        });

        //触发自动刷新
        refreshLayout.autoRefresh();

    }

    private void initData(Context mContext, int page) {

        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentDate = sDateFormat.format(new Date());
        HashMap<String, String> addParams = new HashMap<>();
        addParams.put("page", page + "");
        addParams.put("beginDate", "1970-12-08 10:00:00");
        addParams.put("endDate", currentDate);
        addParams.put("paytype", "6");
        APIRetrofit.getAPIService().orderGetPosOrderL(RXRequest.getXingPosParams(addParams, mContext))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OrderGetPosOrderLEntity>() {


                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull OrderGetPosOrderLEntity orderGetPosOrderLEntity) {
//                        if (Tools.isAvailable(orderGetPosOrderLEntity))return;
                        int success = orderGetPosOrderLEntity.getSuccess();
                        if(success == 1) {
                            int PageCount = orderGetPosOrderLEntity.getPageCount();
                            int PageIndex = orderGetPosOrderLEntity.getPageIndex();

                            LogUtils.e("PageCount",
                                    "================================" + PageCount);
                            LogUtils.e("pageIndex",
                                    "================================" + PageIndex);
                            List<OrderGetPosOrderLEntity.DataBean> data =
                                    orderGetPosOrderLEntity.getData();
                            if(data.size() > 0) {
                                if(PageIndex > 1) {
                                    LogUtils.e("loadmore",
                                            "================================" + data.size());
                                    stickrecycleadpter.loadmore(data);
                                } else {
                                    LogUtils.e("refresh",
                                            "================================" + data.size());
                                    stickrecycleadpter.refresh(data);
                                }
                            } else {
                                ToastUtils.showToast(getActivity(), "没有数据了");
                            }
                        } else if(success == -100 | success == -200) {
                            //// TODO: 2017/12/9 0009 绑定guid  界面
                            SharedPreferencesUtils.remove(getActivity(), "autologin");
                            SharedPreferencesUtils.remove(getActivity(),
                                    "remberpassword");
                            startActivity(new Intent(getActivity(),
                                    BangGuidActivity.class));
                        } else if(success == -300 || success == -2 || success == -3 || success == -6) {
                            //// TODO: 2017/12/9 0009 去登录的界面
                            com.blankj.utilcode.util.ToastUtils.showShortSafe(orderGetPosOrderLEntity.getErrMsg());
                            SharedPreferencesUtils.remove(getActivity(), "autologin");
                            SharedPreferencesUtils.remove(getActivity(),
                                    "remberpassword");
                            startActivity(new Intent(getActivity(), LoginActivity.class));
                        } else {
                            ToastUtils.showToast(getActivity(),
                                    orderGetPosOrderLEntity.getErrMsg() + "");
                        }

                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        if(e instanceof SocketTimeoutException) {
                            Toast.makeText(mContext, "网络连接超时", Toast.LENGTH_SHORT).show();
                        } else if(e instanceof ConnectException) {
                            Toast.makeText(mContext, "连接失败", Toast.LENGTH_SHORT).show();
                        } else {
                            Log.e("onError:", "error:" + e.getMessage());//R.string
                            // .checknet +
                            Toast.makeText(mContext, "检查网络状态", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
